package com.xiaobai.zhuangxiuguanjia.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.xiaobai.zhuangxiuguanjia.R;
import com.xiaobai.zhuangxiuguanjia.Utils.PhoneCall;
import com.xiaobai.zhuangxiuguanjia.Utils.RequestManager;
import com.xiaobai.zhuangxiuguanjia.Utils.ViewHolder;
import com.xiaobai.zhuangxiuguanjia.activities.FreeActivity;
import com.xiaobai.zhuangxiuguanjia.activities.MydemandActivity;
import com.xiaobai.zhuangxiuguanjia.activities.SimpleActivity;
import com.xiaobai.zhuangxiuguanjia.activities.WebActivity;
import com.xiaobai.zhuangxiuguanjia.adapters.HeadPagerAdapter;
import com.xiaobai.zhuangxiuguanjia.model.CommonData;
import com.xiaobai.zhuangxiuguanjia.model.DesignData;
import com.xiaobai.zhuangxiuguanjia.model.HeadInfo;
import com.xiaobai.zhuangxiuguanjia.model.HeadViewData;
import com.xiaobai.zhuangxiuguanjia.model.HeadViewInfo;
import com.xiaobai.zhuangxiuguanjia.model.Info;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;


public class HeadFragment extends Fragment
        implements PullToRefreshBase.OnRefreshListener2, View.OnClickListener,
        AdapterView.OnItemClickListener {

//    List<DesignData> designDataList;
    List<HeadViewData> headViewDataList;
    List<CommonData> commonDataList;
    private MyAdapter adapter;
    ImageView imageMenu;
    View topView;
    ViewPager viewPager;
    private RequestQueue requestQueue;
    private HeadPagerAdapter headPagerAdapter;
    private ImageView imageDesign, imagePrice, imageRead, imageCompany;
    private ListView listView;
    private List<View> pageList;


    public HeadFragment() {
        // Required empty public constructor
    }

    PullToRefreshListView ptrListView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        designDataList = new LinkedList<DesignData>();
        headViewDataList = new LinkedList<HeadViewData>();
        commonDataList = new LinkedList<CommonData>();
        requestQueue = RequestManager.getInstance(getActivity()).getRequestQueue();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.d("onCreateView", "onCreateView");
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_head, container, false);
        ptrListView = (PullToRefreshListView) view.findViewById(R.id.head_ptrListView);


        adapter = new MyAdapter(commonDataList);
        imageMenu = (ImageView) view.findViewById(R.id.head_image_menu);
        imageMenu.setOnClickListener(this);
        ptrListView.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        ptrListView.setOnRefreshListener(this);
        topView = getHeadView();
        listView = ptrListView.getRefreshableView();
        listView.addHeaderView(topView);
        headPagerAdapter.notifyDataSetChanged();
        ptrListView.setAdapter(adapter);

        ptrListView.setOnItemClickListener(this);
        return view;
    }

    private View getHeadView() {
        Log.d("getHeadView", "getHeadView");
        topView = LayoutInflater.from(getActivity()).inflate(R.layout.head_headview_layout, null);
        viewPager = (ViewPager) topView.findViewById(R.id.head_headview_pager);
        imageDesign = (ImageView) topView.findViewById(R.id.head_image_design);
        if (imageDesign != null) {
            imageDesign.setOnClickListener(this);
        }
        imagePrice= (ImageView) topView.findViewById(R.id.head_image_price);
        if (imagePrice != null) {
            imagePrice.setOnClickListener(this);
        }
        imageRead = (ImageView) topView.findViewById(R.id.head_image_read);
        if (imageRead != null) {
            imageRead.setOnClickListener(this);
        }
        imageCompany = (ImageView) topView.findViewById(R.id.head_image_company);
        if (imageCompany != null) {
            imageCompany.setOnClickListener(this);
        }
        String url = "http://mobileapi.to8to.com/index.php?module=ad&action=get&addtype=2&model=ad&cityName=&appid=1&appversion=2.5.1&systemversion=15&appostype=1&to8to_token=&version=2.5";
//        StringBuilder sb = new StringBuilder();
//        sb.append("module").append("=").append("ad");
//        sb.append("&action").append("=").append("get");
//        sb.append("&addtype").append("=").append("2");
//        sb.append("&model").append("=").append("ad");
//        sb.append("&appid").append("=").append("1");
//        sb.append("&version").append("=").append("2.5");
//        url = url + sb;
//        Log.d("url", "url:" + url);
        JsonObjectRequest request = new JsonObjectRequest(
                url,
                null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("HeadView", "HeadView:" + response);
                        HeadViewInfo headViewInfo = new HeadViewInfo();
                        headViewInfo.parseJSON(response);
                        List<HeadViewData> headViewDatas = headViewInfo.getHeadViewDataList();
                        headViewDataList.clear();
                        headViewDataList.addAll(headViewDatas);
                    }

                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                    }
                }
        );
        requestQueue.add(request);
        pageList = new ArrayList<View>();
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        for (int i = 0; i < headViewDataList.size(); i++) {
            View view = inflater.inflate(R.layout.head_headview, null);
            String imgurl = headViewDataList.get(i).getImgurl();
            ImageView imageView = (ImageView) view.findViewById(R.id.head_headView_image);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            ImageLoader imageLoader = RequestManager.getInstance(getActivity()).getImageLoader();
            imageLoader.get(imgurl, imageLoader.getImageListener(imageView, R.mipmap.ic_launcher, R.mipmap.ic_launcher));
            pageList.add(view);
        }
        headPagerAdapter = new HeadPagerAdapter(pageList);
        viewPager.setAdapter(headPagerAdapter);
        headPagerAdapter.notifyDataSetChanged();
        return topView;
    }


    @Override
    public void onResume() {
        super.onResume();
        String url = "http://mobileapi.to8to.com/smallapp.php?";
        StringBuilder sb = new StringBuilder();
        sb.append("model").append("=").append("homepage");
        sb.append("&page").append("=").append("3");
        sb.append("&action").append("=").append("gjlist");
        url = url + sb;
//        RequestQueue requestQueue = RequestManager.getInstance(getActivity()).getRequestQueue();
        JsonObjectRequest request = new JsonObjectRequest(
                url,
                null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("JSONObject", "JSONObject:" + response);
                        HeadInfo headInfo = new HeadInfo();
                        headInfo.parseJSON(response);
                        List<DesignData> dataList = headInfo.getDataList();
                        List<CommonData> datas = new LinkedList<CommonData>();
                        for (int i = 0; i < dataList.size(); i++) {
                            DesignData designData = dataList.get(i);
                            List<CommonData> commonDatas = designData.getCommonDataList();
                            datas.addAll(commonDatas);
                        }
                        commonDataList.clear();
                        commonDataList.addAll(datas);
                        Log.d("DesignDataList", "designDataList:" + response);
                        adapter.notifyDataSetChanged();
                    }

                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }
        );
        requestQueue.add(request);
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {

    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.head_image_menu:
            PhoneCall.phoneCall(getActivity());
                break;
            case R.id.head_image_design:
                Intent intent = new Intent(getActivity(), MydemandActivity.class);
                startActivity(intent);
                break;
            case R.id.head_image_price:
                Intent intent1 = new Intent(getActivity(), FreeActivity.class);
                startActivity(intent1);
                break;
            case R.id.head_image_read:
                Intent intent2 = new Intent(getActivity(), SimpleActivity.class);
                startActivity(intent2);
                break;
            case R.id.head_image_company:
                break;
        }
    }
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Log.d("ListPisition","ListPosition:"+position);
        String webUrl = commonDataList.get(position-2).getWebUrl();
        String title = commonDataList.get(position-2).getTitle();
        Intent intent = new Intent();
        intent.putExtra("url", webUrl);
        intent.putExtra("title", title);
        intent.setClass(getActivity(), WebActivity.class);
        startActivity(intent);
    }

    public class MyAdapter extends BaseAdapter {
        private List<CommonData> commonDataList;

        public MyAdapter(List<CommonData> commonDataList) {
            this.commonDataList = commonDataList;
        }

        @Override
        public int getCount() {
            int ret = 0;
            if (commonDataList != null) {
                ret = commonDataList.size();
            }
            return ret;
        }

        @Override
        public Object getItem(int position) {
            Object ret = null;
            if (commonDataList != null) {
                ret = commonDataList.get(position);
            }
            return ret;
        }

        @Override
        public int getViewTypeCount() {
            return 4;
        }

        @Override
        public int getItemViewType(int position) {
            int ret = 0;
            if (commonDataList != null) {
                if (commonDataList.get(position).getRows().isEmpty())
                {
                    ret = 1;
                }else {
                    ret = 2;
                }
            }
            return ret;
        }

        @Override
        public long getItemId(int position) {
            long ret = 0;
            if (commonDataList != null) {
                ret = position;
            }
            return ret;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Log.d("position","position:"+position);
            CommonData commonData = commonDataList.get(position);
            String article_id = commonData.getArticle_id();
            Log.d("type", "type:" + article_id);
            if (!article_id.isEmpty()) {
                if (convertView == null)
                    convertView = LayoutInflater.from(getActivity()).inflate(R.layout.head_item_list_special, parent, false);
                ImageView imageView = ViewHolder.getView(convertView, R.id.head_item_image);
                TextView txtTite = ViewHolder.getView(convertView, R.id.head_item_title);
                TextView txtContent = ViewHolder.getView(convertView, R.id.head_item_content);
                TextView txtDate = ViewHolder.getView(convertView, R.id.head_item_date);
                TextView txtClick = ViewHolder.getView(convertView, R.id.head_item_click);
                String filename = commonData.getFilename();
                ImageLoader imageLoader = RequestManager.getInstance(getActivity()).getImageLoader();
                imageLoader.get(
                        filename,
                        imageLoader.getImageListener(imageView, R.mipmap.ic_launcher, R.mipmap.ic_launcher)
                );
                String summary = commonDataList.get(position).getSummary();
                txtContent.setText(summary);
                String title = commonDataList.get(position).getTitle();
                txtTite.setText(title);
                String puttime = commonDataList.get(position).getPuttime();
                txtDate.setText(puttime);
                String click = commonDataList.get(position).getClick();
                txtClick.setText(click);
            } else  {

                    if (convertView == null)
                        convertView = LayoutInflater.from(getActivity()).inflate(R.layout.head_item_list_image, parent, false);
                    ImageView image1 = ViewHolder.getView(convertView, R.id.head_item2_image1);
                    ImageView image2 = ViewHolder.getView(convertView, R.id.head_item2_image2);
                    ImageView image3 = ViewHolder.getView(convertView, R.id.head_item2_image3);
                    TextView txtTitle = ViewHolder.getView(convertView, R.id.head_item2_title);
                    TextView txtDate = ViewHolder.getView(convertView, R.id.head_item2_date);
                    TextView txtClick = ViewHolder.getView(convertView, R.id.head_item2_click);
                    TextView txtImageCount = ViewHolder.getView(convertView, R.id.head_item2_imageCount);
                String title = commonData.getTitle();
                    txtTitle.setText(title);
                    String edittime = commonData.getEdittime();
                    txtDate.setText(edittime);
                    String rows = commonData.getRows();
                    txtImageCount.setText(rows);
                    List<Info> infoList = commonData.getInfoList();
                    String likenum = infoList.get(0).getLikenum();
                    txtClick.setText(likenum);
                    String filename1 = infoList.get(0).getFilename();
                    ImageLoader imageLoader = RequestManager.getInstance(getActivity()).getImageLoader();
                    imageLoader.get(
                            filename1,
                            imageLoader.getImageListener(image1, R.mipmap.ic_launcher, R.mipmap.ic_launcher)
                    );
                    String filename2 = infoList.get(1).getFilename();
                    imageLoader.get(
                            filename2,
                            imageLoader.getImageListener(image2, R.mipmap.ic_launcher, R.mipmap.ic_launcher)
                    );
                    String filename3 = infoList.get(2).getFilename();
                    imageLoader.get(
                            filename3,
                            imageLoader.getImageListener(image3, R.mipmap.ic_launcher, R.mipmap.ic_launcher)
                    );

            }
            return convertView;
        }
    }
}
